﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StriveEngine;
using StriveEngine.Core;
using StriveEngine.Tcp.Server;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using Seagull.BarTender.Print;
namespace PrintfServer
{
    class WebSocket
    {
        private ITcpServerEngine tcpServerEngine;
        private bool hasTcpServerEngineInitialized;
        private MyBartender mybartender = null;//new MyBartender();
        private IPEndPoint Client_ipe = null;
        public void OutLog(String Msg)
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + Msg);
            }
        }
        public void StartServer(int Port)
        {
            if (this.tcpServerEngine == null)
            {
                this.tcpServerEngine = NetworkEngineFactory.CreateTextTcpServerEngine(Port, new DefaultTextContractHelper("\0"));//DefaultTextContractHelper是StriveEngine内置的ITextContractHelper实现。使用UTF-8对EndToken进行编码。 
            }

            if (this.hasTcpServerEngineInitialized)
            {
                this.tcpServerEngine.ChangeListenerState(true);
            }
            else
            {
                this.InitializeTcpServerEngine();
            }

        }
        public void Stop()
        {
            if (!this.tcpServerEngine.IsListening)
            {
                return;
            }
            this.tcpServerEngine.ChangeListenerState(false);

        }

        private void InitializeTcpServerEngine()
        {
            this.tcpServerEngine.ClientCountChanged += new CbDelegate<int>(tcpServerEngine_ClientCountChanged);
            this.tcpServerEngine.ClientConnected += new CbDelegate<System.Net.IPEndPoint>(tcpServerEngine_ClientConnected);
            this.tcpServerEngine.ClientDisconnected += new CbDelegate<System.Net.IPEndPoint>(tcpServerEngine_ClientDisconnected);
            this.tcpServerEngine.MessageReceived += new CbDelegate<IPEndPoint, byte[]>(tcpServerEngine_MessageReceived);
            this.tcpServerEngine.Initialize();
            this.hasTcpServerEngineInitialized = true;
        }

        void tcpServerEngine_ClientConnected(System.Net.IPEndPoint ipe)
        {
            if (Client_ipe != null)
            {
                if (Client_ipe.Address.ToString() != ipe.Address.ToString() || Client_ipe.Port != ipe.Port)
                {
                    this.tcpServerEngine.CloseClient(Client_ipe); //确保一台设备只能一个客户端接入。
                }

            }
            if (mybartender == null)
            {
                mybartender = new MyBartender();
            }
            Client_ipe = ipe;
            string msg = string.Format("{0} 上线", ipe);
            //SendResultToWeb("", 8, "", "");
            OutLog(msg);

        }
        void tcpServerEngine_ClientDisconnected(System.Net.IPEndPoint ipe)
        {
            string msg = string.Format("{0} 下线", ipe);
            if (ipe.Port == Client_ipe.Port)
            {
                tcpServerEngine.CloseClient(ipe);
                Client_ipe = null;
            }
            OutLog(msg);
        }
        public void tcpServerEngine_SendMsgToClient(String Sendmsg)
        {
            string msg = "";
            try
            {
                if (!this.tcpServerEngine.IsClientOnline(Client_ipe))
                {
                    msg = string.Format("{0} 不在线", Client_ipe);
                    OutLog(msg);
                    return;
                }
                byte[] bMsg = System.Text.Encoding.UTF8.GetBytes(Sendmsg);//消息使用UTF-8编码
                this.tcpServerEngine.SendMessageToClient(Client_ipe, bMsg);
            }
            catch
            {
                msg = string.Format("{0} 不在线", Client_ipe);
                OutLog(msg);
            }
        }
        void tcpServerEngine_MessageReceived(IPEndPoint client, byte[] bMsg)
        {
            string msg = System.Text.Encoding.UTF8.GetString(bMsg); //消息使用UTF-8编码
            msg = msg.Substring(0, msg.Length); //将结束标记"\0"剔除
            string abc = string.Format("收到 {0} 发来的消息：{1}", client, msg);
            OutLog(msg);
            CommandParse(msg);


        }
        void tcpServerEngine_ClientCountChanged(int count)
        {
            Console.WriteLine("当前客户端在线数量：" + count.ToString());
        }

        void CommandParse(String msg)
        {
            try
            {
                List<IPEndPoint> list = this.tcpServerEngine.GetClientList();
                JObject root_obj = JObject.Parse(msg);
                String Type = root_obj["Type"].ToString();
                if(Type == "GetPrintNameList")
                {
                    SendResultToWeb("", 8, "", "");
                    return;
                }
                else
                {
                    String PrintName = root_obj["PrintName"].ToString();
                    OutLog("PrintName");
                    String TaskId = root_obj["TaskID"].ToString();
                    OutLog("TaskID");
                    String EPC = root_obj["EPC"].ToString();
                    OutLog("EPC");
                    String Template = root_obj["Template"].ToString();
                    OutLog("Template");
                    String detailId = root_obj["detailId"].ToString();
                    OutLog("detailId");
                    String itemNo = root_obj["itemNo"].ToString();
                    OutLog("itemNo");
                    JArray DataObj = JArray.Parse(root_obj["Data"].ToString());
                    List<KeyValuePair<string, string>> PintParmList = new List<KeyValuePair<string, string>>();
                    for (int i = 0; i < DataObj.Count; i++)
                    {
                        JObject itemObj = JObject.Parse(DataObj[i].ToString());
                        foreach (var x in itemObj)
                        {
                            Console.WriteLine("{0} : {1}", x.Key, x.Value);
                            PintParmList.Add(new KeyValuePair<string, string>(x.Key.ToString(), x.Value.ToString()));
                        }
                    }
                    bool ret = false;
                    ret = mybartender.BartenderPrint(PrintName, PintParmList, Template);
                    if (ret == false)
                    {
                        OutLog("打印失败");
                        SendResultToWeb(TaskId, 2, "打印标签失败", EPC);
                    }
                    else
                    {
                        OutLog("打印成功");
                        JObject Info_obj = new JObject();
                        Info_obj.Add("detailId", detailId);
                        Info_obj.Add("itemNo", itemNo);
                        SendResultToWeb(TaskId, 0, Info_obj.ToString(), EPC);
                    }

                    return;
                }
                
            }
            catch (Exception ex)
            {
                OutLog("解析指令失败");
                SendResultToWeb("", 1, "解析指令失败", "");
                return;
            }
        }
        public void SendResultToWeb(String TaskId, int Type, String ErrorInfo, string epc)
        {
            JObject SendObj = new JObject();
            if (Type == 0)//打印成功
            {
                SendObj.Add(new JProperty("TaskId", TaskId));
                SendObj.Add(new JProperty("success", 0));
                SendObj.Add(new JProperty("Info", ErrorInfo));
                SendObj.Add(new JProperty("epc", epc));
            }
            else if (Type == 1)//解析打印指令失败
            {
                SendObj.Add(new JProperty("TaskId", TaskId));
                SendObj.Add(new JProperty("success", 1));
                SendObj.Add(new JProperty("Info", ErrorInfo));
                SendObj.Add(new JProperty("epc", epc));
            }
            else if (Type == 2) //打印标签失败
            {
                SendObj.Add(new JProperty("TaskId", TaskId));
                SendObj.Add(new JProperty("success", 2));
                SendObj.Add(new JProperty("Info", ErrorInfo));
                SendObj.Add(new JProperty("epc", epc));
            }
            else if (Type == 8)
            {
                SendObj.Add(new JProperty("success", 8));
                JArray PrintArray = new JArray();
                Printers printers = new Printers();
                foreach (Printer printer in printers)
                {
                    JObject ItemObj = new JObject();
                    ItemObj.Add(new JProperty("Name", printer.PrinterName));
                    PrintArray.Add(ItemObj);
                }
                SendObj.Add(new JProperty("Info", PrintArray));
                SendObj.Add(new JProperty("Default", printers.Default.PrinterName));
            }
            OutLog("发送:" + SendObj.ToString());
            tcpServerEngine_SendMsgToClient(SendObj.ToString());
        }
    
    }
}
